package com.t4l.server.rpcservices;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.t4l.client.services.login.LoginService;
import com.t4l.server.ApplicationListener;
import com.t4l.server.UserService;
import com.t4l.server.entity.T4LUser;
import com.t4l.shared.exceptions.T4LException;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/t4l/login")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	@Override
	public String validateFacebookLogin(String accessToken, int expiresIn)
			throws T4LException {
		JSONObject authFacebookLoginJson = UserService.authFacebookLogin(
				accessToken, expiresIn);
		authFacebookLoginJson.put("accessToken", accessToken);
		authFacebookLoginJson.put("expiresIn", expiresIn);
		getThreadLocalRequest().getSession(true).setAttribute("user-info",
				authFacebookLoginJson);
		return authFacebookLoginJson.toString();
	}

	@Override
	public String getUserInfo() {
		HttpSession session = getThreadLocalRequest().getSession();
		if (session == null) {
			return null;
		}
		JSONObject jso = (JSONObject) session.getAttribute("user-info");
		if (jso == null) {
			return null;
		}
		return jso.toString();
	}

	@Override
	public String validateT4LLogin(String email, String password)
			throws IllegalArgumentException, T4LException {

		EntityManager em = ApplicationListener.getEM();
		Query query = em
				.createQuery("SELECT t4lU FROM "
						+ T4LUser.class.getName()
						+ " t4lU WHERE t4lU.email = :_email AND t4lU.password = :_password");
		query.setParameter("_email", email);
		query.setParameter("_password", password);
		try{
		T4LUser t4lUser = (T4LUser) query.getSingleResult();
		JSONObject json = t4lUser.toJson();
		getThreadLocalRequest().getSession(true)
				.setAttribute("user-info", json);
		return json.toString();
		}catch (NoResultException nre) {
			throw new T4LException("failed login");
		}
	}

}
